/**
 * 新闻相关的自定义Hook
 *
 * 提供新闻数据的获取、搜索和管理功能
 */
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { newsService, NewsListParams } from '../services/newsService';
import { News, NewsCreate, NewsUpdate } from '../types';

// 查询键常量
const QUERY_KEYS = {
  news: ['news'] as const,
  newsItem: (id: number) => ['news', id] as const,
  latestNews: ['news', 'latest'] as const,
  featuredNews: ['news', 'featured'] as const,
};

/**
 * 获取新闻列表
 */
export const useNews = (params: NewsListParams = {}) => {
  return useQuery({
    queryKey: [...QUERY_KEYS.news, params],
    queryFn: () => newsService.getNews(params),
    staleTime: 5 * 60 * 1000, // 5分钟内数据被认为是新鲜的
  });
};

/**
 * 获取单个新闻详情
 */
export const useNewsDetail = (id: number) => {
  return useQuery({
    queryKey: QUERY_KEYS.newsItem(id),
    queryFn: () => newsService.getNewsDetail(id),
    enabled: !!id,
  });
};

/**
 * 获取最新新闻（用于前台显示）
 */
export const useLatestNews = (limit: number = 6) => {
  return useQuery({
    queryKey: [...QUERY_KEYS.latestNews, limit],
    queryFn: () => newsService.getLatestNews(limit),
    staleTime: 10 * 60 * 1000, // 10分钟内数据被认为是新鲜的
  });
};

/**
 * 获取置顶新闻
 */
export const useFeaturedNews = () => {
  return useQuery({
    queryKey: QUERY_KEYS.featuredNews,
    queryFn: () => newsService.getFeaturedNews(),
    staleTime: 15 * 60 * 1000, // 15分钟内数据被认为是新鲜的
  });
};

/**
 * 搜索新闻
 */
export const useSearchNews = (keyword: string, params: Omit<NewsListParams, 'keyword'> = {}) => {
  return useQuery({
    queryKey: [...QUERY_KEYS.news, 'search', keyword, params],
    queryFn: () => newsService.searchNews(keyword, params),
    enabled: !!keyword.trim(), // 只有当关键词不为空时才执行搜索
    staleTime: 2 * 60 * 1000, // 搜索结果2分钟内有效
  });
};

/**
 * 创建新闻
 */
export const useCreateNews = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (data: NewsCreate) => newsService.createNews(data),
    onSuccess: () => {
      // 创建成功后，使相关查询失效
      queryClient.invalidateQueries({
        queryKey: QUERY_KEYS.news,
        exact: false // 匹配所有以 ['news'] 开头的查询键
      });
      queryClient.invalidateQueries({ queryKey: QUERY_KEYS.latestNews });
      queryClient.invalidateQueries({ queryKey: QUERY_KEYS.featuredNews });
    },
  });
};

/**
 * 更新新闻
 */
export const useUpdateNews = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ id, data }: { id: number; data: NewsUpdate }) =>
      newsService.updateNews(id, data),
    onSuccess: (updatedNews) => {
      // 更新缓存中的数据
      queryClient.setQueryData(
        QUERY_KEYS.newsItem(updatedNews.id),
        updatedNews
      );

      // 使所有新闻相关查询失效（包括带参数的查询）
      queryClient.invalidateQueries({
        queryKey: QUERY_KEYS.news,
        exact: false // 这会匹配所有以 ['news'] 开头的查询键
      });
      queryClient.invalidateQueries({ queryKey: QUERY_KEYS.latestNews });
      queryClient.invalidateQueries({ queryKey: QUERY_KEYS.featuredNews });
    },
  });
};

/**
 * 删除新闻
 */
export const useDeleteNews = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (id: number) => newsService.deleteNews(id),
    onSuccess: (_, deletedId) => {
      // 从缓存中移除数据
      queryClient.removeQueries({ queryKey: QUERY_KEYS.newsItem(deletedId) });

      // 使列表查询失效
      queryClient.invalidateQueries({
        queryKey: QUERY_KEYS.news,
        exact: false // 匹配所有以 ['news'] 开头的查询键
      });
      queryClient.invalidateQueries({ queryKey: QUERY_KEYS.latestNews });
      queryClient.invalidateQueries({ queryKey: QUERY_KEYS.featuredNews });
    },
  });
};

/**
 * 新闻管理的综合Hook
 */
export const useNewsManagement = () => {
  const createMutation = useCreateNews();
  const updateMutation = useUpdateNews();
  const deleteMutation = useDeleteNews();

  return {
    // 创建
    createNews: createMutation.mutate,
    isCreating: createMutation.isPending,
    createError: createMutation.error,

    // 更新
    updateNews: updateMutation.mutate,
    isUpdating: updateMutation.isPending,
    updateError: updateMutation.error,

    // 删除
    deleteNews: deleteMutation.mutate,
    isDeleting: deleteMutation.isPending,
    deleteError: deleteMutation.error,

    // 重置错误状态
    resetErrors: () => {
      createMutation.reset();
      updateMutation.reset();
      deleteMutation.reset();
    },
  };
};